package com.leyou.trade.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 虎哥
 */
@Component
public class PayHelper {

    @Autowired
    private WXPayConfigImpl payConfig;

    @Autowired
    private WXPay wxPay;

    public String getPayUrl(Long orderId, Long totalFee, String desc) {
        // 1.准备请求参数：
        Map<String, String> data = new HashMap<>();
        // 商品描述
        data.put("body", desc);
        // 订单编号
        data.put("out_trade_no", orderId.toString());
        // 交易金额
        data.put("total_fee", totalFee.toString());
        // 终端IP
        data.put("spbill_create_ip", payConfig.getSpbillCreateIp());
        // 交易类型
        data.put("trade_type", payConfig.getTradeType());

        try {
            // 2.下单
            Map<String, String> resp = wxPay.unifiedOrder(data);

            // 3.校验结果
            // 3.1.校验returnCode
            checkReturnCode(resp);
            // 3.2.校验resultCode
            checkResultCode(resp);
            // 3.3.校验签名
            checkSignature(data);
            // 4.获取支付链接
            String codeUrl = resp.get("code_url");
            if (StringUtils.isBlank(codeUrl)) {
                throw new RuntimeException("微信下单失败，支付链接为空！");
            }
            return codeUrl;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void checkSignature(Map<String, String> data){
        boolean isValid = false;
        try {
            isValid = wxPay.isResponseSignatureValid(data);
        } catch (Exception e) {
            throw new RuntimeException("无效的签名");
        }
        if (!isValid) {
            // 无效的签名
            throw new RuntimeException("无效的签名");
        }
    }

    public void checkResultCode(Map<String, String> resp) {
        String resultCode = resp.get("result_code");
        if ("FAIL".equals(resultCode)) {
            throw new RuntimeException(resp.get("err_code_des"));
        }
    }

    public void checkReturnCode(Map<String, String> resp) {
        String returnCode = resp.get("return_code");
        if ("FAIL".equals(returnCode)) {
            throw new RuntimeException(resp.get("return_msg"));
        }
    }
}
